<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Data;
use App\Models\Member;
use App\Models\Question;
use App\Models\QuestionMember;
use App\Services\ExcelExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class QuestionController extends BaseController {

    /**
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $params = $request->all();
//        print_r($params);die;
        $build = Question::query();
        if (isset($params['status'])){
            $build->where('status', $params['status']);
        }

        $build->orderBy('num', 'desc')->orderBy('created_at', 'desc');
        $pageSize = $request->input('pageSize', 50);

        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    public function onIndex(Request $request)
    {
        $params = $request->all();
        $build = Question::query();

        if (!isset($params['status'])) {
            # code...
            $build->whereIn('status', [Question::QUESTION_PASS_BIG, Question::QUESTION_PASS_SMALL]);
        }else{
            $build->where('status', $params['status']);

        }
        $build->orderBy('num', 'desc')->orderBy('created_at', 'desc');
        $pageSize = $request->input('pageSize', 50);



        $data = $build->paginate($pageSize);
        return $this->success($data);
    }

    public function audit($questionId, Request $request)
    {
        $params = $request->all();
        $questionData = Question::query()->where('question_id', $questionId)->first();

        if ($questionData['status'] != Question::QUESTION_DEFAULT){
            return $this->errorCode('10001', [], '问题已经被审核过，请勿重复审核');
        }

        if (!$questionData){
            return $this->errorCode('10002', [], '问题不存在');
        }

        if (!in_array($params['status'], [Question::QUESTION_PASS_BIG, Question::QUESTION_PASS_SMALL, Question::QUESTION_REFUSE])){
            return $this->errorCode('10003', [], '状态非法');
        }

        $result = $questionData->update(['status' => $params['status']]);
        return $this->success($result, '审核成功');


    }

    public function create(Request $request)
    {
        $params = $request->all();
        if (!isset($params['name']) || $params['name'] == '')
        {
            return $this->errorCode('10001', [], '问题name参数错误');

        }
        $name = $params['name'];

        $memberId =$params['member_id'];
        if (!isset($params['member_id']) || $params['member_id'] == '')
        {
            return $this->errorCode('10001', [], 'member参数错误');
        }

        $result = Question::query()->create(['name' => $name, 'member_id' => $memberId]);

        return $this->success($result, '添加成功');

    }

    public function destroy($id, Request $request)
    {
        $question = Question::query()->where('question_id', $id)->first();

        if (!$question){
            return $this->errorCode('10001', [], '问题不存在');
        }

        try {
            $result = $question->delete();
        } catch (\Exception $e) {
            return $this->errorCode('10001', [], '删除失败');
        }
        return $this->success($result, '删除成功');

    }


    public function update($id, Request $request)
    {
        $params = $request->all();
        $fillAble = ['province_info', 'team_info', 'rm_info', 'dm_info'];
        unset($params['token']);
        $data = Member::query()->where('member_id', $id)->first();
        if (!$data){
            throw new AppException('find_member_is_fail');
        }

        unset($params['member_id']);
        $result = Member::query()->where('member_id', $id)->update($params);
        //修改data数据
        if ($request){
            Data::query()->where('member_id', $id)->update($params);
        }
        return $this->success($result, '修改成功');
    }

    public function vote($id, Request $request)
    {
        $params = $request->all();
        $questionData = Question::query()->where('question_id', $id)->first();

        if ($params['member_id'] == ''){
            return $this->errorCode('10003', [], '投票人id不能为空');
        }

        if (!$questionData){
            return $this->errorCode('10002', [], '问题不存在');
        }


        if (!in_array($questionData['status'], [Question::QUESTION_PASS_BIG, Question::QUESTION_PASS_SMALL])) {
           return $this->errorCode('10001', [], '问题不是审核通过状态，不能投票');
        }

        $memberQuestion =  QuestionMember::query()->where('member_id', $params['member_id'])->where('question_id', $id)->first();
        if ($memberQuestion){
            return $this->errorCode('10005', [], '此问题您已经投过票，不能投票');
        }

        $memberQuestion = QuestionMember::query()->where('member_id', $params['member_id'])->count();

        if ($memberQuestion >= 3){
            return $this->errorCode('10004', [], '您投票次数已够3次，不能投票');
        }

        $result = QuestionMember::query()->create(['member_id' => $params['member_id'], 'question_id'=> $id]);

        return $this->success($result, '投票成功');
    }

    /**
     * 导出excel
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws AppException
     */
    public function export(Request $request)
    {
        try {
            $directory = storage_path();
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = [
                'name' => '内容', 'num' => '投票数', 'created_at' => '创建日期'
            ];
            $widthArray = ['A' => 100, 'B' => 10, 'C' => 10, 'D' => 10, 'E' => 10];
            $build = Question::query();
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $build, $header, '', 2000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();die;
            throw new AppException('export_fail');
        }
    }


}